{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{% if asset %}编辑资产{% else %}新增资产{% endif %}</title>
  <link href="{% static 'vendor/bootstrap/bootstrap.min.css' %}" rel="stylesheet">
  <link href="{% static 'vendor/fontawesome/all.min.css' %}" rel="stylesheet">
  <style>
    body { padding: 12px; background: #fafbfc; }
    .form-text { font-size: .85rem; }
    .section-title { font-weight: 600; color: #495057; margin: 18px 0 8px; }
    .card-like { background: #fff; border: 1px solid #e9ecef; border-radius: 8px; padding: 12px; }
  </style>
</head>
<body>
  <div class="container-fluid" id="asset-meta" data-asset-id="{% if asset %}{{ asset.id }}{% endif %}">
    {% if messages %}
    <div class="mb-2">
      {% for message in messages %}
        <div class="alert alert-{{ message.tags }} mb-2" role="alert">{{ message }}</div>
      {% endfor %}
    </div>
    {% endif %}
    <div class="row">
      <div class="col-12 col-lg-10">
        <h5 class="mb-3 d-flex align-items-center gap-2">
          {% if asset %}编辑资产{% else %}新增资产{% endif %}
          <small class="text-muted">|</small>
          <span class="badge bg-info text-dark" id="org-badge" title="当前所属组织">
            {% if asset and asset.ledger and asset.ledger.organization %}
                {{ asset.ledger.organization.name }}
            {% elif organization_id and organizations %}
                {% for org in organizations %}{% if org.id == organization_id %}{{ org.name }}{% endif %}{% endfor %}
            {% else %}
                未选择组织
            {% endif %}
          </span>
        </h5>

        <form id="asset-form" method="post" action="{% if asset %}{% url 'assets:asset_update' asset.id %}?modal=1{% else %}{% url 'assets:asset_create' %}?modal=1{% endif %}" enctype="multipart/form-data" class="card-like">
          {% csrf_token %}
          <input type="hidden" name="modal" value="1">

          <!-- 将 asset_form.html 的核心表单片段复用：为避免重复，这里直接拷贝了相同字段结构 -->
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="name" class="form-label">资产名称 *</label>
                <input type="text" class="form-control" id="name" name="name" value="{% if asset %}{{ asset.name }}{% else %}{{ name|default:'' }}{% endif %}" required>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="asset_number" class="form-label">资产编号 *</label>
                <input type="text" class="form-control" id="asset_number" name="asset_number" value="{% if asset %}{{ asset.asset_number }}{% else %}{{ asset_number|default:'' }}{% endif %}" required>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="category" class="form-label">资产类别 *</label>
                <select class="form-select" id="category" name="category" required>
                  <option value="">请选择资产类别</option>
                  {% for category in categories %}
                    <option value="{{ category.id }}" {% if asset and asset.category_id == category.id or category_id|add:"0" == category.id %}selected{% endif %}>{{ category.name }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="status" class="form-label">资产状态 *</label>
                <select class="form-select" id="status" name="status" required>
                  <option value="idle" {% if asset and asset.status == 'idle' or status == 'idle' %}selected{% endif %}>闲置</option>
                  <option value="in_use" {% if asset and asset.status == 'in_use' or status == 'in_use' %}selected{% endif %}>在用</option>
                  <option value="borrowed" {% if asset and asset.status == 'borrowed' or status == 'borrowed' %}selected{% endif %}>已借出</option>
                  <option value="maintenance" {% if asset and asset.status == 'maintenance' or status == 'maintenance' %}selected{% endif %}>维修中</option>
                  <option value="faulty" {% if asset and asset.status == 'faulty' or status == 'faulty' %}selected{% endif %}>故障</option>
                  <option value="scrapped" {% if asset and asset.status == 'scrapped' or status == 'scrapped' %}selected{% endif %}>已报废</option>
                </select>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="organization" class="form-label">所属组织（账簿归属）</label>
                <select class="form-select" id="organization" name="organization">
                  <option value="">请选择组织</option>
                  {% if organizations %}
                    {% for org in organizations %}
                      <option value="{{ org.id }}" {% if asset and asset.ledger and asset.ledger.organization_id == org.id %}selected{% elif organization_id|add:"0" == org.id %}selected{% endif %}>{{ org.name }}</option>
                    {% endfor %}
                  {% endif %}
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3" id="ledger-field">
                <label for="ledger" class="form-label">账簿</label>
                <select class="form-select" id="ledger" name="ledger">
                  <option value="">请选择账簿</option>
                  {% if ledgers %}
                    {% for ledger in ledgers %}
                      <option value="{{ ledger.id }}" data-org="{{ ledger.organization.id }}" data-org-name="{{ ledger.organization.name }}" data-code="{{ ledger.code }}" {% if asset and asset.ledger_id == ledger.id %}selected{% elif ledger_id|add:"0" == ledger.id %}selected{% endif %}>
                        {% if not organization_id %}
                          {% if not asset or not asset.ledger or not asset.ledger.organization_id %}
                            {{ ledger.organization.name }} /
                          {% endif %}
                        {% endif %}
                        {{ ledger.name }}
                      </option>
                    {% endfor %}
                  {% endif %}
                </select>
                <div class="form-text" id="ledger-help-normal">可先选择“所属组织”以便仅显示该组织下的账簿。</div>
                <div class="form-text text-warning d-none" id="ledger-help-empty">该组织下暂无账簿，将仅使用“所属组织”来标识资产归属，可直接提交。</div>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="department" class="form-label">所属部门</label>
                <select class="form-select" id="department" name="department">
                  <option value="">请选择部门</option>
                  {% for department in departments %}
                    <option value="{{ department.id }}" {% if asset and asset.department_id == department.id or department_id|add:"0" == department.id %}selected{% endif %}>{{ department.name }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="location" class="form-label">位置</label>
                <select class="form-select" id="location" name="location">
                  <option value="">请选择位置</option>
                  {% for location in locations %}
                    <option value="{{ location.id }}" {% if asset and asset.location_id == location.id or location_id|add:"0" == location.id %}selected{% endif %}>{{ location.name }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="user" class="form-label">使用人</label>
                <select class="form-select" id="user" name="user">
                  <option value="">请选择使用人</option>
                  {% for user in users %}
                    <option value="{{ user.id }}" {% if asset and asset.user_id == user.id or user_id|add:"0" == user.id %}selected{% endif %}>{{ user.username }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="supplier" class="form-label">供应商</label>
                <select class="form-select" id="supplier" name="supplier">
                  <option value="">请选择供应商</option>
                  {% for supplier in suppliers %}
                    <option value="{{ supplier.id }}" {% if asset and asset.supplier_id == supplier.id or supplier_id|add:"0" == supplier.id %}selected{% endif %}>{{ supplier.name }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="contract" class="form-label">合同</label>
                <select class="form-select" id="contract" name="contract">
                  <option value="">请选择合同</option>
                  {% for contract in contracts %}
                    <option value="{{ contract.id }}" {% if asset and asset.contract_id == contract.id or contract_id|add:"0" == contract.id %}selected{% endif %}>{{ contract.name }}</option>
                  {% endfor %}
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="purchase_date" class="form-label">启用日期 *</label>
                <input type="date" class="form-control" id="purchase_date" name="purchase_date" value="{% if asset %}{{ asset.purchase_date|date:'Y-m-d' }}{% else %}{{ purchase_date|default:'' }}{% endif %}" required>
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="purchase_price" class="form-label">采购价格 *</label>
                <input type="number" class="form-control" id="purchase_price" name="purchase_price" step="0.01" value="{% if asset %}{{ asset.purchase_price }}{% else %}{{ purchase_price|default:'' }}{% endif %}" required>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="warranty_period" class="form-label">保修期(月)</label>
                <input type="number" class="form-control" id="warranty_period" name="warranty_period" value="{% if asset %}{{ asset.warranty_period }}{% else %}{{ warranty_period|default:'' }}{% endif %}">
              </div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="depreciation_rate" class="form-label">折旧率(%)</label>
                <input type="number" class="form-control" id="depreciation_rate" name="depreciation_rate" step="0.01" value="{% if asset %}{{ asset.depreciation_rate }}{% else %}{{ depreciation_rate|default:'' }}{% endif %}">
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label for="description" class="form-label">描述</label>
            <textarea class="form-control" id="description" name="description" rows="3">{% if asset %}{{ asset.description }}{% else %}{{ description|default:'' }}{% endif %}</textarea>
          </div>

          <!-- 图片上传区 -->
          <div class="mb-3">
            <label for="image" class="form-label">资产图片</label>
            {% if asset and asset.get_primary_image_url %}
              <div class="mb-2">
                <img src="{{ asset.get_primary_image_url }}" alt="{{ asset.name }}" style="max-width: 200px; max-height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #dee2e6;">
                <div class="mt-1"><small class="text-muted">当前图片</small></div>
              </div>
            {% endif %}
            <input type="file" class="form-control" id="image" name="image" accept="image/*">
            <div class="form-text">支持 JPG、PNG、GIF 格式，建议尺寸不超过 2MB</div>
          </div>

          <div class="mb-3">
            <label class="form-label">额外图片 
              {% if asset %}
                <small class="text-muted">(当前: {{ asset.get_image_count }}/10)</small>
              {% else %}
                <small class="text-muted">(最多10张)</small>
              {% endif %}
            </label>
            <div id="additional-images">
              {% if asset %}
                {% for img in asset.asset_images.all %}
                  <div class="d-flex align-items-center mb-2 existing-image" data-image-id="{{ img.id }}">
                    <img src="{{ img.get_image_url }}" alt="{{ img.title }}" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px; margin-right: 10px;">
                    <div class="flex-grow-1">
                      <input type="text" class="form-control form-control-sm mb-1" name="existing_image_title_{{ img.id }}" value="{{ img.title }}" placeholder="图片标题">
                      <textarea class="form-control form-control-sm" name="existing_image_description_{{ img.id }}" rows="2" placeholder="图片描述">{{ img.description }}</textarea>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-danger ms-2" onclick="removeExistingImage('{{ img.id }}')">
                      <i class="fa fa-trash"></i>
                    </button>
                  </div>
                {% endfor %}
              {% endif %}
            </div>
            {% if not asset or asset.can_add_more_images %}
              <button type="button" class="btn btn-sm btn-outline-primary" onclick="addImageUpload()">
                <i class="fa fa-plus"></i> 添加图片
              </button>
            {% else %}
              <small class="text-muted">已达到图片上限</small>
            {% endif %}
          </div>

          <div class="mb-3 d-flex gap-2">
            <button id="submit-btn" type="submit" class="btn btn-primary">{% if asset %}更新{% else %}创建{% endif %}</button>
            <button id="cancel-btn" type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">关闭</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script>
  let imageUploadCounter = 0;
  const maxImages = 10;
  function addImageUpload() {
    const existingImages = document.querySelectorAll('.existing-image').length;
    const newImages = document.querySelectorAll('.new-image-upload').length;
    const mainImage = document.querySelector('input[name="image"]').files.length;
    if (existingImages + newImages + mainImage >= maxImages) { alert(`最多只能上传${maxImages}张图片`); return; }
    imageUploadCounter++;
    const container = document.getElementById('additional-images');
    const imageUploadDiv = document.createElement('div');
    imageUploadDiv.className = 'd-flex align-items-start mb-2 new-image-upload';
    imageUploadDiv.innerHTML = `
      <div class="flex-grow-1">
        <input type="file" class="form-control form-control-sm mb-1" name="additional_images_${imageUploadCounter}" accept="image/*" onchange="validateImageFile(this)">
        <input type="text" class="form-control form-control-sm mb-1" name="additional_image_title_${imageUploadCounter}" placeholder="图片标题">
        <textarea class="form-control form-control-sm" name="additional_image_description_${imageUploadCounter}" rows="2" placeholder="图片描述"></textarea>
      </div>
      <button type="button" class="btn btn-sm btn-outline-danger ms-2" onclick="removeImageUpload(this)"><i class="fa fa-trash"></i></button>`;
    container.appendChild(imageUploadDiv);
  }
  function validateImageFile(input) {
    const file = input.files[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) { alert('图片文件大小不能超过2MB'); input.value = ''; return false; }
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
      if (!allowedTypes.includes(file.type)) { alert('只支持 JPG、PNG、GIF 格式的图片'); input.value = ''; return false; }
    }
    return true;
  }
  function removeImageUpload(button) { button.closest('.new-image-upload').remove(); }
  function removeExistingImage(imageId) {
    if (confirm('确定要删除这张图片吗？')) {
      const imageDiv = document.querySelector(`[data-image-id="${imageId}"]`);
      if (imageDiv) imageDiv.style.display = 'none';
      const hiddenInput = document.createElement('input');
      hiddenInput.type = 'hidden';
      hiddenInput.name = 'delete_images';
      hiddenInput.value = imageId;
      document.querySelector('form').appendChild(hiddenInput);
    }
  }
  document.getElementById('image')?.addEventListener('change', function(e){
    const file = e.target.files[0];
    if (!validateImageFile(this)) return;
    if (file) {
      const reader = new FileReader();
      reader.onload = function(ev){
        const old = document.getElementById('image-preview'); if (old) old.remove();
        const preview = document.createElement('div');
        preview.id = 'image-preview'; preview.className = 'mt-2';
        preview.innerHTML = `<img src="${ev.target.result}" alt="预览" style="max-width: 200px; max-height: 200px; object-fit: cover; border-radius: 8px; border: 1px solid #dee2e6;">
          <div class="mt-1"><small class="text-muted">新图片预览 (${(file.size / (1024 * 1024)).toFixed(2)}MB)</small></div>`;
        document.getElementById('image').parentNode.appendChild(preview);
      };
      reader.readAsDataURL(file);
    }
  });
  document.addEventListener('DOMContentLoaded', function(){
    // If messages exist, scroll to top; if success, auto-close & refresh parent
    const hasAlert = document.querySelector('.alert');
    if (hasAlert) { window.scrollTo({ top: 0, behavior: 'smooth' }); }
    const successAlert = document.querySelector('.alert-success');
    if (successAlert) {
      const metaEl = document.getElementById('asset-meta');
      const assetIdRaw = metaEl ? metaEl.getAttribute('data-asset-id') : '';
      const assetId = assetIdRaw ? parseInt(assetIdRaw, 10) : null;
      // brief notice to user
      const note = document.createElement('div');
      note.className = 'text-success mb-2';
      note.textContent = '已保存，窗口将自动关闭并刷新...';
      successAlert.parentNode.insertBefore(note, successAlert.nextSibling);
      setTimeout(function(){
        // try to notify parent (list/detail) to refresh
        try {
          window.parent.postMessage({ type: 'assetSaved', id: assetId }, '*');
        } catch (e) {}
        // try to close modal in same document
        try {
          if (typeof bootstrap !== 'undefined'){
            const modalEl = document.querySelector('.modal.show');
            if (modalEl){
              const instance = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
              instance.hide();
            }
          }
        } catch (e) {}
        // try to close parent modal if content is inside iframe
        try {
          const parentDoc = window.parent && window.parent.document;
          if (parentDoc){
            const pModal = parentDoc.querySelector('.modal.show');
            if (pModal && window.parent.bootstrap){
              const pInstance = window.parent.bootstrap.Modal.getInstance(pModal) || new window.parent.bootstrap.Modal(pModal);
              pInstance.hide();
            }
          }
        } catch (e) {}
        // finally, refresh parent or current window
        try { if (window.parent && window.parent !== window) { window.parent.location.reload(); return; } } catch (e) {}
        window.location.reload();
      }, 800);
    }

    // Prevent double submit
    const form = document.getElementById('asset-form');
    const submitBtn = document.getElementById('submit-btn');
    if (form && submitBtn){
      form.addEventListener('submit', function(){
        submitBtn.disabled = true;
        submitBtn.textContent = '处理中...';
      });
    }

    // Fallback: if not inside a Bootstrap modal, make cancel go back
    const cancelBtn = document.getElementById('cancel-btn');
    if (cancelBtn){
      cancelBtn.addEventListener('click', function(e){
        const inModal = !!document.querySelector('.modal.show');
        if (!inModal) { window.history.back(); }
      });
    }

    const orgSelect = document.getElementById('organization');
    const ledgerSelect = document.getElementById('ledger');
    const orgBadge = document.getElementById('org-badge');
    const ledgerField = document.getElementById('ledger-field');
    const ledgerHelpNormal = document.getElementById('ledger-help-normal');
    const ledgerHelpEmpty = document.getElementById('ledger-help-empty');
    if (!orgSelect || !ledgerSelect) return;
    const allLedgerOptions = Array.from(ledgerSelect.querySelectorAll('option')).filter(opt => opt.value !== '');
    const placeholder = ledgerSelect.querySelector('option[value=""]');
    function getFilteredLedgerOptions(orgId) {
      return !orgId ? allLedgerOptions : allLedgerOptions.filter(opt => String(opt.getAttribute('data-org')) === String(orgId));
    }
    function rebuildLedgerOptions(orgId){
      const prevSelected = ledgerSelect.value; // preserve current selection before rebuild
      ledgerSelect.innerHTML=''; if (placeholder) ledgerSelect.appendChild(placeholder.cloneNode(true));
      const fragment = document.createDocumentFragment();
      const toShow = getFilteredLedgerOptions(orgId);
      toShow.forEach(opt => fragment.appendChild(opt.cloneNode(true)));
      ledgerSelect.appendChild(fragment);
      // try restore previous selection if still available
      if (prevSelected && Array.from(ledgerSelect.options).some(o => o.value === prevSelected)) {
        ledgerSelect.value = prevSelected;
      } else {
        ledgerSelect.value = '';
      }
      // toggle ledger field visibility based on availability
      const availableCount = Array.from(ledgerSelect.options).filter(o => o.value !== '').length;
      if (availableCount === 0){
        ledgerField.classList.add('d-none');
        ledgerHelpNormal?.classList.add('d-none');
        ledgerHelpEmpty?.classList.remove('d-none');
      } else {
        ledgerField.classList.remove('d-none');
        ledgerHelpNormal?.classList.remove('d-none');
        ledgerHelpEmpty?.classList.add('d-none');
      }
    }
    function selectDefaultLedgerForOrg(orgId){
      const options = Array.from(ledgerSelect.options).filter(o => o.value !== '');
      if (options.length === 0) { ledgerSelect.value = ''; return; }
      // If a valid value already selected and still visible, keep it
      const current = ledgerSelect.value;
      if (current && options.some(o => o.value === current)) return;

      // Special handling for group org: if org text contains '集团', prefer ledger name containing '集团'
      const selectedOrgText = orgSelect.options[orgSelect.selectedIndex]?.textContent || '';
      if (selectedOrgText.includes('集团')){
        const groupLedger = options.find(o => (o.textContent || '').includes('集团')) || options[0];
        ledgerSelect.value = groupLedger?.value || '';
        return;
      }
      // If only one ledger, select it
      if (options.length === 1){ ledgerSelect.value = options[0].value; return; }
      // Otherwise select the first as a reasonable default
      ledgerSelect.value = options[0].value;
    }
    function updateOrgBadge(){
      const orgId = orgSelect.value;
      if (orgId){ const selected = orgSelect.options[orgSelect.selectedIndex]; orgBadge.textContent = selected ? selected.textContent.trim() : '未选择组织'; return; }
      const ledgerOpt = ledgerSelect.options[ledgerSelect.selectedIndex];
      const fromLedgerName = ledgerOpt ? ledgerOpt.getAttribute('data-org-name') : '';
      orgBadge.textContent = fromLedgerName ? fromLedgerName : '未选择组织';
    }
    // Initial build and default selection
    rebuildLedgerOptions(orgSelect.value); selectDefaultLedgerForOrg(orgSelect.value); updateOrgBadge();
    orgSelect.addEventListener('change', function(e){ rebuildLedgerOptions(e.target.value); selectDefaultLedgerForOrg(e.target.value); updateOrgBadge(); });
    ledgerSelect.addEventListener('change', function(){ if (!orgSelect.value) updateOrgBadge(); });
  });
  </script>
</body>
</html>
